﻿using FSM.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FSM.Web.Models.Fileter
{
    /// <summary>
    /// 异常处理过虑特性
    /// </summary>
    public class ResultExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 同步处理异常
        /// </summary>
        /// <param name="context">异常信息上下文</param>
        public override void OnException(ExceptionContext context)
        {
            DataResultModel drm = new DataResultModel();
            if (!context.ExceptionHandled)
            {
                drm.success = false;
                if (context.Exception.InnerException != null && !string.IsNullOrEmpty(context.Exception.InnerException.Message))
                {
                    drm.message = context.Exception.InnerException.Message;
                }
                else
                {
                    drm.message = context.Exception.Message;
                }
                context.Result = new JsonResult(drm);
                context.ExceptionHandled = true;
            }

            base.OnException(context);
        }

        /// <summary>
        /// 异步等待处理异常
        /// </summary>
        /// <param name="context">异常信息上下文</param>
        /// <returns></returns>
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }
    }
}
